package cn.mgm.senior.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtil {
  private static DataSource dataSource;
  // 在项目启动时,创建连接池对象,赋值给 dataSource
  static {
      try {
          Properties properties = new Properties();
          InputStream resourceAsStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
          properties.load(resourceAsStream);
          dataSource = DruidDataSourceFactory.createDataSource(properties);
      } catch (Exception e) {
          throw new RuntimeException(e);
      }
  }

  public static Connection getConnection(){
      try {
          return  dataSource.getConnection();
      } catch (SQLException e) {
          throw new RuntimeException(e);
      }
  }


  public static void release(Connection connection){
      try {
          connection.close();
      }catch (SQLException e) {
          throw new RuntimeException(e);
      }
  }
}
